package com.cweb.admin.model.sys.sys_menu_info.service;

import com.cweb.admin.model.sys.sys_menu_info.entity.SysMenuInfo;
import com.cweb.admin.model.sys.sys_menu_info.mapper.SysMenuInfoMapper;
import com.cweb.admin.serivce.authority.UserLoginService;
import com.cweb.framework.base.serivce.BaseMybatisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 系统-系统菜单信息表 服务实现类
 * @since 2020-08-17
 */
@Service
public class SysMenuInfoService extends BaseMybatisService<SysMenuInfoMapper, SysMenuInfo> {
    @Autowired
    private UserLoginService userLoginService;

    /**
     * 菜单组合查询
     */
    public List<SysMenuInfo> selectMenu(boolean bolAll) {
        // 判断要查询的角色
        String[] ids = null;
        if (!bolAll) {
            ids = userLoginService.getCurLoginToken().getRole();
            if (null == ids && !"super".equals(userLoginService.getCurLoginToken().getType())) {
                return new ArrayList<SysMenuInfo>();
            }
        }
        // 菜单信息查询
        List<SysMenuInfo> listMenu = this.getBaseMapper().selectMenuByRoles(ids);
        // 菜单嵌套处理
        List<SysMenuInfo> listRet = new ArrayList<>();
        // 一级菜单
        for (SysMenuInfo firstSysMenuInfo : listMenu) {
            if (null != firstSysMenuInfo.getParent() && !firstSysMenuInfo.getParent().equals(0L)) {
                continue;
            }
            // 二级菜单
            List<SysMenuInfo> listSecond = new ArrayList<>();
            for (SysMenuInfo secondSysMenuInfo : listMenu) {
                if (!firstSysMenuInfo.getId().equals(secondSysMenuInfo.getParent())) {
                    continue;
                }
                // 三级菜单
                List<SysMenuInfo> listThird = new ArrayList<>();
                for (SysMenuInfo thirdSysMenuInfo : listMenu) {
                    if (!secondSysMenuInfo.getId().equals(thirdSysMenuInfo.getParent())) {
                        continue;
                    }
                    listThird.add(thirdSysMenuInfo);
                }
                listThird.sort(menuSort);
                secondSysMenuInfo.setChildren(listThird);
                listSecond.add(secondSysMenuInfo);
            }
            listSecond.sort(menuSort);
            firstSysMenuInfo.setChildren(listSecond);
            listRet.add(firstSysMenuInfo);
        }
        listRet.sort(menuSort);
        return listRet;
    }
    // 菜单排序用
    Comparator menuSort = new Comparator<SysMenuInfo>() {
        @Override
        public int compare(SysMenuInfo o1, SysMenuInfo o2) {
            return o1.getOrder().compareTo(o2.getOrder());
        }
    };
}
